//
//  JZHTableViewCell.m
//  JZHTest
//
//  Created by yyt on 14-8-4.
//  Copyright (c) 2014年 yyt. All rights reserved.
//

#import "JZHTableViewCell.h"
#import "JZHTheDiary.h"

#import "JZHFriendsCircleViewController.h"


@implementation JZHTableViewCell
@synthesize icon;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        //头像，用户昵称，内容
        [self addContentTextView];
        
        //图片，时间，赞和评论
        [self addContentPhotoView];
        
        //赞和评论的内容
        [self addContentContentView];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(HiddenZanAndComment:) name:@"closeZanAndComment" object:nil];
        isNotification = NO;
        
        // Initialization code
    }
    return self;
}

#pragma mark 头像，用户昵称，内容
///头像，用户昵称，内容
/*
 icon       头像       tag = 9001
 nickName   用户昵称    tag = 9002
 content    内容       tag = 9003
 */
- (void)addContentTextView
{
    //头像
    icon = [[UIImageView alloc]initWithFrame:CGRectMake(14, 15, 45, 45)];
    [icon.layer setCornerRadius:5];
    [icon.layer setBorderColor:[UIColor grayColor].CGColor];
    [icon.layer setBorderWidth:0.5];
    [icon setUserInteractionEnabled:YES];
    [icon setTag:9001];
    [self addSubview:icon];
    
    UITapGestureRecognizer *tapIcon = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(userInfoAction:)];
    [icon addGestureRecognizer:tapIcon];
    
    //昵称
    UILabel *nickName = [[UILabel alloc]initWithFrame:CGRectMake(67, 9, 233, 21)];
    [nickName setTextColor:[UIColor blackColor]];
    [nickName setFont:[UIFont systemFontOfSize:15]];
    [nickName setTag:9002];
    [self.contentView addSubview:nickName];
    
    //内容
    UILabel *content = [[UILabel alloc]initWithFrame:CGRectMake(67, 30, 233, 1)];
    [content setTextColor:[UIColor blackColor]];
    [content setFont:[UIFont systemFontOfSize:14]];
    [content setNumberOfLines:0];
    [content setTag:9003];
    [self.contentView addSubview:content];
}

///图片，时间，赞和评论
/*
 photo      图片       tag = 8001
 time       时间       tag = 8002
 comment    赞         tag = 8003
 */
- (void)addContentPhotoView
{
    //图片
    UIView *photo = [[UIView alloc]initWithFrame:CGRectMake(67, 31, 233, 1)];
    [photo setBackgroundColor:[UIColor clearColor]];
    [photo setTag:8001];
    [self addSubview:photo];
    
    //时间
    UILabel *time = [[UILabel alloc]initWithFrame:CGRectMake(67, 40, 120, 20)];
    [time setTextColor:[UIColor grayColor]];
    [time setFont:[UIFont systemFontOfSize:12]];
    [time setTag:8002];
    [self.contentView addSubview:time];
    
    //赞和评论按钮
    UIButton *comment = [[UIButton alloc]initWithFrame:CGRectMake(263, 30, 57, 40)];
    [comment setImage:[UIImage imageNamed:@"朋友圈cell上的标记"] forState:UIControlStateNormal];
    [comment addTarget:self action:@selector(zanAndCommentAction:) forControlEvents:UIControlEventTouchUpInside];
    [comment setTag:8003];
    [comment setBackgroundColor:[UIColor whiteColor]];
    [self addSubview:comment];
    
    //赞和评论视图
    UIView *zanAndCommentView = [[UIView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 59, comment.frame.origin.y - 15, 0, 35)];
    [zanAndCommentView setBackgroundColor:[UIColor colorWithRed:78/255.0 green:78/255.0 blue:78/255.0 alpha:1]];
    [zanAndCommentView.layer setBorderColor:[UIColor grayColor].CGColor];
    [zanAndCommentView.layer setBorderWidth:0.5];
    [zanAndCommentView.layer setCornerRadius:5];
    [zanAndCommentView setTag:8004];
    [self addSubview:zanAndCommentView];
    
    //赞按钮
    UIButton *zan = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 70, 25)];
    [zan setBackgroundColor:[UIColor clearColor]];
//    [zan.layer setBorderColor:[UIColor blackColor].CGColor];
//    [zan.layer setBorderWidth:0.5];
    [zan.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [zan setTitle:@"赞" forState:UIControlStateNormal];
    [zan setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [zan addTarget:self action:@selector(zanAction:) forControlEvents:UIControlEventTouchUpInside];
    [zanAndCommentView addSubview:zan];
    
    UIView *zanAndCommentLine = [[UIView alloc]initWithFrame:CGRectMake(zan.frame.origin.x + zan.frame.size.width + 2, 5, 0.3, 25)];
    [zanAndCommentLine setBackgroundColor:[UIColor colorWithRed:10/255.0 green:63/255.0 blue:13/255.0 alpha:1]];
    [zanAndCommentView addSubview:zanAndCommentLine];
    
    //评论按钮
    UIButton *commentBtn = [[UIButton alloc]initWithFrame:CGRectMake(80, 5, 70, 25)];
    [commentBtn setBackgroundColor:[UIColor clearColor]];
//    [commentBtn.layer setBorderColor:[UIColor blackColor].CGColor];
//    [commentBtn.layer setBorderWidth:0.5];
    [commentBtn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [commentBtn setTitle:@"评论" forState:UIControlStateNormal];
    [commentBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    [zan addTarget:self action:@selector(commentAction:) forControlEvents:UIControlEventTouchUpInside];
    [zanAndCommentView addSubview:commentBtn];
    
    
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(zanAction:)];
    [zan addGestureRecognizer:tap1];
    
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(commentAction:)];
    [commentBtn addGestureRecognizer:tap2];
}

//赞和评论的内容
/*
 commentContent    赞和评论的内容         tag = 7001
 */
- (void)addContentContentView
{
    UIView *commentContent = [[UIView alloc]initWithFrame:CGRectMake(67, 60, 233, 300)];
    [commentContent setBackgroundColor:[UIColor clearColor]];
    [commentContent setTag:7001];
    [self.contentView addSubview:commentContent];
}


#pragma mark - 设置数据
///设置数据
- (CGFloat)setCellTopData:(JZHTheDiary *)diary
{
    myDiary = diary;
    
    float height = 0;
    
#pragma 第一部分内容
    //头像
    [ImageCache imageUrl:diary.userHeadImage UiImageview:icon];

    //昵称
    UILabel *nickName = (UILabel *)[self.contentView viewWithTag:9002];
    [nickName setText:diary.name];
    
    //内容
    UILabel *content = (UILabel *)[self.contentView viewWithTag:9003];
    NSString *strContent = diary.content;
    CGSize size = [strContent sizeWithFont:content.font constrainedToSize:CGSizeMake(content.frame.size.width, 1000)  lineBreakMode:0];
    [content setText:strContent];
    [content setFrame:CGRectMake(content.frame.origin.x,
                                content.frame.origin.y,
                                content.frame.size.width,
                                 size.height)];
    height = content.frame.origin.y + content.frame.size.height + 5;
    
#pragma 第二部分内容
    //显示内容中的图片
    height = [self addPhotoData:diary.images andStartY:height] + height + 5;
    
    //时间
    UILabel *time = (UILabel *)[self.contentView viewWithTag:8002];
    [time setText:[self theTimeReCheck:diary.tdDate]];
    [time setFrame:CGRectMake(time.frame.origin.x, height + 5, time.frame.size.width, time.frame.size.height)];
    
    //赞或评论按钮
    UIButton *comment = (UIButton *)[self viewWithTag:8003];
    [comment setFrame:CGRectMake(comment.frame.origin.x, height - 5, comment.frame.size.width, comment.frame.size.height)];
    
    //赞和评论视图
    UIView *zanAndCommentView = (UIView *)[self viewWithTag:8004];
    [zanAndCommentView setFrame:CGRectMake(zanAndCommentView.frame.origin.x,
                                           comment.frame.origin.y + 2,
                                           zanAndCommentView.frame.size.width,
                                           zanAndCommentView.frame.size.height)];
    height = height + time.frame.size.height + 5;
    
    [self bringSubviewToFront:comment];
    
#pragma 第三部分内容
    NSMutableDictionary *dictZanAndComment = [NSMutableDictionary dictionary];
    [dictZanAndComment setValue:myDiary.arrCommentList forKey:@"commentList"];
    [dictZanAndComment setValue:myDiary.arrPraiseList forKey:@"praiseList"];
    
    height = height + [self addCommentContentData:dictZanAndComment andStartY:height] + 10;
    
    
    return height + 5;
}

///显示赞和评论的内容
- (float)addCommentContentData:(NSDictionary *)content andStartY:(CGFloat)height
{
    if (content.allKeys.count == 0)
    {
        return 0;
    }
    
    UIView *commentContent = (UIView *)[self.contentView viewWithTag:7001];
    
    float controlY = 10;
    NSArray *arrayZan = [NSArray array];
    NSArray *arrayComment = [NSArray arrayWithObjects:[NSDictionary dictionary], nil];
    if ([content objectForKey:@"praiseList"])
    {
        arrayZan = [NSArray arrayWithArray:myDiary.arrPraiseList];
    }
    
    if ([content objectForKey:@"commentList"])
    {
        arrayComment = [NSArray arrayWithArray:myDiary.arrCommentList];
    }
    
    if (arrayZan.count == 0 && arrayComment.count == 0)
    {
        return 0;
    }

    //设置背景图片
    UIImage *imageBackground = [UIImage imageNamed:@"朋友圈评论背景色"];
    imageBackground = [imageBackground stretchableImageWithLeftCapWidth:floorf(imageBackground.size.width/2) topCapHeight:floorf(imageBackground.size.height/2)];
    
    UIImageView *imageViewBackground = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, commentContent.frame.size.width, commentContent.frame.size.height)];
    [imageViewBackground setImage:imageBackground];
    [imageViewBackground setAutoresizingMask:UIViewAutoresizingFlexibleHeight];
    [commentContent addSubview:imageViewBackground];
    
    
    if (arrayZan.count > 0)
    {
    #pragma 赞的内容
        //赞的人
        UILabel *zan = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 220, 0)];
        [zan setFont:[UIFont systemFontOfSize:13]];
        NSString *strZanName = @"👍";
        if (arrayZan.count > 0)
        {
            NSDictionary *item = [arrayZan objectAtIndex:0];
            strZanName = [NSString stringWithFormat:@"%@%@", strZanName, [item objectForKey:@"userName"]];
        }

        for (int i = 1; i < arrayZan.count; i++)
        {
            NSDictionary *item = [arrayZan objectAtIndex:i];
            strZanName = [NSString stringWithFormat:@"%@, %@", strZanName, [item objectForKey:@"userName"]];
        }
        CGSize size = [strZanName sizeWithFont:zan.font constrainedToSize:CGSizeMake(zan.frame.size.width, 1000)  lineBreakMode:0];
        [zan setText:strZanName];
        [zan setNumberOfLines:0];
        [zan setFrame:CGRectMake(zan.frame.origin.x, zan.frame.origin.y, zan.frame.size.width, size.height)];
        [commentContent addSubview:zan];
        
        if (strZanName.length > 0)
        {
            controlY = size.height + 15;
        }
    }
    
    //赞结束时下面的线
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, controlY, commentContent.frame.size.width, 0.5)];
    [line setBackgroundColor:[UIColor colorWithRed:225/255.0 green:225/255.0 blue:225/255.0 alpha:1]];
    if (arrayZan.count > 0 && arrayComment.count > 0)
    {
        [commentContent addSubview:line];
    }
    
    
#pragma 评论的内容
    for (NSDictionary *item in arrayComment)
    {
        NSString *strName = [item objectForKey:@"userName"];
        NSString *strContent1 = [item objectForKey:@"content"];
        
        UILabel *theContent = [[UILabel alloc]initWithFrame:CGRectMake(10, controlY, 210, 0)];
        [theContent setFont:[UIFont systemFontOfSize:13]];
        [theContent setBackgroundColor:[UIColor clearColor]];
        [theContent setNumberOfLines:0];
        [commentContent addSubview:theContent];
        
        //计算昵称长度
        float nameLength = strName.length;
        //拼接字符串
        NSString *strContent = [NSString stringWithFormat:@"%@: %@", strName, strContent1];
        //计算高度
        CGSize sizeContent = [strContent sizeWithFont:[UIFont systemFontOfSize:13] constrainedToSize:CGSizeMake(210, 1000) lineBreakMode:0];
        
        //设计颜色
        NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:strContent];
        [str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0, nameLength)];
        [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:13.0] range:NSMakeRange(0, nameLength)];
        theContent.attributedText = str;

        //修改uilabel高度
        [theContent setFrame:CGRectMake(theContent.frame.origin.x, theContent.frame.origin.y, theContent.frame.size.width, sizeContent.height + 3)];
        
        //变化高度
        controlY = controlY + sizeContent.height;
    }
    
    [commentContent setFrame:CGRectMake(commentContent.frame.origin.x, height + 5, commentContent.frame.size.width, controlY + 5)];
    
    return controlY + 5;
}

///显示内容中的图片
- (CGFloat)addPhotoData:(NSArray *)array andStartY:(CGFloat)height
{
    UIView *photoView = (UIView *)[self viewWithTag:8001];
    if (array.count == 3) {
        NSLog(@"dadkda");
    }
    
    float photoHeight = 5;
    
    if (array.count == 0)
    {
        photoHeight = 5;
    }
    else if(array.count == 1)
    {
        UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 200, 200)];
        [ImageCache imageUrl:[array objectAtIndex:0] UiImageview:image];
        [image setUserInteractionEnabled:YES];
        [photoView addSubview:image];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageViewBig:)];
        [tap setAccessibilityValue:@"0"];
        [image addGestureRecognizer:tap];
        
        photoHeight = photoHeight + 200;
    }
    else
    {
        for (int i = 0;i < array.count;i++)
        {
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake((i % 3) * 79, (i / 3) * 79, 75, 75)];
            [ImageCache imageUrl:[array objectAtIndex:i] UiImageview:image];
            [image setUserInteractionEnabled:YES];
            [photoView addSubview:image];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapImageViewBig:)];
            [tap setAccessibilityValue:[NSString stringWithFormat:@"%d", i]];
            [image addGestureRecognizer:tap];
        }
        photoHeight = photoHeight + ((array.count - 1) / 3) * 79 + 75;
    }
    
    [photoView setFrame:CGRectMake(photoView.frame.origin.x,
                                   height,
                                   photoView.frame.size.width,
                                   photoHeight)];
    
    return photoHeight;
}

#pragma mark - 赞和评论的方法
- (void)zanAndCommentAction:(UIButton *)sender
{
    if (isNotification)
    {
        isNotification = NO;
        return;
    }
    UIView *zanAndCommentView = (UIView *)[self viewWithTag:8004];
    
    if (zanAndCommentView.frame.origin.x > [UIScreen mainScreen].bounds.size.width - 100)
    {
        [self showComment];
    }
    else
    {
        [self hidenComment];
    }
}

- (void)showComment
{
    UIView *zanAndCommentView = (UIView *)[self viewWithTag:8004];
    
    [UIView animateWithDuration:0.25 animations:^{
        [zanAndCommentView setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 210,
                                               zanAndCommentView.frame.origin.y,
                                               155,
                                               zanAndCommentView.frame.size.height)];
    }];
}

- (void)hidenComment
{
    UIView *zanAndCommentView = (UIView *)[self viewWithTag:8004];
    
    
    [UIView animateWithDuration:0.25 animations:^{
        [zanAndCommentView setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 59,
                                               zanAndCommentView.frame.origin.y,
                                               0,
                                               zanAndCommentView.frame.size.height)];
    }];
}

- (void)zanAction:(UITapGestureRecognizer *)tapGestureRecognizer
{
    UIView *zanAndCommentView = (UIView *)[self viewWithTag:8004];
    [zanAndCommentView setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 59,
                                           zanAndCommentView.frame.origin.y,
                                           0,
                                           zanAndCommentView.frame.size.height)];
    
    if ([self.delegate respondsToSelector:@selector(httpLoadDataZan:)])
    {
        NSString *strID = myDiary.tdid;
        [self.delegate httpLoadDataZan:strID];
    }
}

- (void)commentAction:(UITapGestureRecognizer *)tapGestureRecognizer
{
    UIView *zanAndCommentView = (UIView *)[self viewWithTag:8004];
    [zanAndCommentView setFrame:CGRectMake([UIScreen mainScreen].bounds.size.width - 59,
                                           zanAndCommentView.frame.origin.y,
                                           0,
                                           zanAndCommentView.frame.size.height)];
    
    if ([self.delegate respondsToSelector:@selector(showCommentKeyboard:)])
    {
        [self.delegate showCommentKeyboard:myDiary];
    }
}

#pragma mark 计算时间
- (NSString *)theTimeReCheck:(NSDate *)strTime
{
    if ([NSString stringWithFormat:@"%@",strTime].length < 13)
    {
        return @"";
    }
    
    NSDate *now=[NSDate date];

    NSTimeInterval time=[now timeIntervalSinceDate:strTime];
    
    int days=((int)time)/(3600*24);
    int hours=((int)time)%(3600*24)/3600;
    int min = ((int)time)%(3600*24*60)/60;

    NSString *dateContent;
    if (days > 0)
    {
        dateContent = [NSString stringWithFormat:@"%i天前", days];
    }
    else if(hours > 0)
    {
        dateContent = [NSString stringWithFormat:@"%i小时前", hours];
    }
    else
    {
        dateContent = [NSString stringWithFormat:@"%i分钟前", min];
    }
 
    return dateContent;
}

#pragma mark 点击头像执行的手势方法
- (void)userInfoAction:(UITapGestureRecognizer *)tap
{
    if ([self.delegate respondsToSelector:@selector(pushUserInfoVC:)])
    {
        [self.delegate pushUserInfoVC:myDiary];
    }
}

- (void)awakeFromNib
{

    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self endEditing:YES];
}

- (void)tapImageViewBig:(UITapGestureRecognizer *)tapGestureRecognizer
{
    if ([self.delegate respondsToSelector:@selector(imageViewBig:andIndex:)])
    {
        [self.delegate imageViewBig:myDiary.images andIndex:tapGestureRecognizer.accessibilityValue];
    }
}

- (void)HiddenZanAndComment:(NSNotification *)notification
{
//    UIView *zanAndCommentView = (UIView *)[self viewWithTag:8004];
    
//    if (zanAndCommentView.frame.origin.x > [UIScreen mainScreen].bounds.size.width - 100)
//    {}
//    else
//    {
//        [self hidenComment];
//        isNotification = YES;
//    }
//    [self hidenComment];
}
@end
